<?php
/**
 * Created by PhpStorm.
 * Author: sitenv@aliyun.com
 * CreateTime: 2021/07/09 14:46
 * Blog：www.myblogs.xyz
 */

namespace app\common\model;


use app\common\utils\AesRsa;

class Setting extends Common
{
    protected $name = 'setting';
    protected $pk = 'key';

    public function settingFind($key = '')
    {
        if (empty($key)) return [];
        $exist = $this->where('key', $key)->count();
        if ($exist){
            $field_path = APP_PATH . 'setting/' . $key .'.json';
            if (!file_exists($field_path)){
                file_put_contents($field_path, json_encode([$key=>'']));
            }
            $json_data = file_get_contents($field_path);
            $data = json_decode($json_data, true);
            /*// 数据信息解密
            $encrypt_val = $data[$key];
            $aes_esa = new AesRsa();
            $decrypt_val = $aes_esa->decryption($encrypt_val);
            return $decrypt_val;*/
            return $data[$key];
        }
        return [];
    }

    public function insetSetting($key = '', $val = [])
    {
        if (empty($key) || empty($val)) return false;
        /*// 数据信息加密
        $aes_esa = new AesRsa();
        $val = $aes_esa->encryption($val);*/
        $exist = $this->where('key', $key)->count();
        if ($exist){
            $rows = $this->where('key', $key)->update(['val'=>json_encode($val)]);
            if (empty($rows)){
                return false;
            }
        }else{
            $rows = $this->insert(['key'=>$key,'val'=>json_encode($val)]);
            if (empty($rows)){
                return false;
            }
        }
        $field_path = APP_PATH . 'setting/' . $key .'.json';
        file_put_contents($field_path, json_encode([$key=>$val]));
        return true;
    }

    /**
     * 极光信息推送
     * @param $alert
     * @param $alias
     * @param array $extras
     * @param string $app_type
     * @return bool
     */
    public function ruleExec($alert, $alias, $extras = [], $app_type = '')
    {
        try{
            import('push.api.Push');
            $setting_model = new Setting();
            $setting_data = $setting_model->settingFind('push' . $app_type);
            if (empty($setting_data)){
                return false;
            }
            $push = new \Push($setting_data['app_key'], $setting_data['master_secret']);
            $ios_notification = [
                'alert' => $alert,
                'badge' => '+1',
                'extras'=>$extras
            ];
            $android_notification = [
                'alert'=>$alert,
                'title'=>$extras['contents'],
                'extras'=>$extras
            ];
            if (empty($setting_data['environment'])){
                $push->develop($alert, $alias, $ios_notification, $android_notification);
            }else{
                $push->production($alert, $alias, $ios_notification, $android_notification);
            }
        } catch(\Exception $e){

        }
        return true;
    }

    /**
     * 获取GPS设备TOKEN信息
     * @param $token_type
     * @return mixed|string
     */
    public function getToken($token_type = 'dr_gps_token')
    {
        import('ego.DrGps');
        $ego = new \DrGps();
        $setting_data = $this->settingFind($token_type);
        if (empty($setting_data['token'])){
            $server_token = $ego->token();
            $this->insetSetting($token_type, ['token'=>$server_token,'last_time'=>NEW_TIME]);
        }else{
            if (NEW_TIME - $setting_data['last_time'] > 7000){
                $server_token = $ego->token();
                $this->insetSetting($token_type, ['token'=>$server_token,'last_time'=>NEW_TIME]);
            }else{
                $server_token = $setting_data['token'];
            }
        }
        return $server_token;
    }

    /**
     * 获取access_token信息
     * @param $token_type
     * @return mixed|string
     */
    public function getAccessToken($token_type = 'applet')
    {
        $setting_data = $this->settingFind($token_type);
        if (empty($setting_data['access_token'])){
            $access_token = $this->accessToken();
            $this->insetSetting($token_type, ['access_token'=>$access_token,'last_time'=>NEW_TIME]);
        }else{
            if (NEW_TIME - $setting_data['last_time'] > 7000){
                $access_token = $this->accessToken();
                $this->insetSetting($token_type, ['access_token'=>$access_token,'last_time'=>NEW_TIME]);
            }else{
                $access_token = $setting_data['access_token'];
            }
        }
        return $access_token;
    }

    private function accessToken()
    {
        $setting_data = $this->settingFind('wx_applet');
        if (empty($setting_data['app_id']) || empty($setting_data['app_key'])){
            return '';
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential';
        $url .= '&appid=' . $setting_data['app_id'] . '&secret=' . $setting_data['app_key'];
        $data = file_get_contents($url);
        $json_data = json_decode($data, true);
        if (empty($json_data['access_token'])){
            return '';
        }
        return $json_data['access_token'];
    }

}